<template>
  <div class="preview-task">
    <el-row class="header" type="flex" justify="space-between">
      <div>
        <span class="header-title">【ID{{ previewObj.id }}】{{ previewObj.title }}</span>
        <span class="overdue-text" v-if="previewObj.overdue === '逾期'">逾期</span>
      </div>
      <!-- <el-button type="primary" v-if="!isHand" size="small" icon="el-icon-edit"
        @click="handleUpdateTask(previewObj.id)">编辑</el-button> -->
    </el-row>
    <el-row :gutter="10" class="content">
      <el-col class="content-left" :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
        <el-tabs v-model="activeName">
          <el-tab-pane v-if="previewObj.issued_superior !== -1 && queryData.showPager" name="dealWithSign">
            <span slot="label"><i class="el-icon-message"></i> 处理签</span>
            <pager :isReportTask="true" :pager="previewObj"></pager>
            <!-- <proposed-pager /> -->
          </el-tab-pane>
          <!-- 详细信息 -->
          <el-tab-pane name="baseInfo">
            <span slot="label"><i class="el-icon-date"></i> 详情信息</span>
            <div class="contcontent-left-des" v-html="previewObj.body"></div>

            <div class="fileList" v-if="hasTaskFile">
              <div class="text">附件</div>
              <div class="items">
                <div class="item" v-for="(item,index) in previewObj.taskFile" :key="index">
                  <image-type :width="20" :fileType="item.fileType"></image-type>
                  <span class="name" @click="previewFile(item, isFromTaskList ? 1 : 0)">{{ item.name }}</span>
                  <div v-if="item.fileType === 'doc' || item.fileType === 'docx'" class="toolBox">
                    <el-dropdown trigger="hover">
                      <span class="el-dropdown-link">
                        套红模板<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(pager, index) in pagerClassifyOptions" :key="index"
                          @click.native="handSelectPager(item, pager.id)">{{ pager.name }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </div>
              </div>
            </div>
            <div class="fileUpload-history" v-if="previewObj.data_type === '文件上传'">
                <div class="title" v-if="historyFileNum">
                  <i class="el-icon-paperclip"></i>
                  <span class="name">已上传文件记录</span>
                </div>
                <history-file :taskId="previewObj.id" @setHistoryFileNum="getHistoryFileNum"></history-file>
              </div>
            <div class="table-model">
              <TableInfo :taskId="taskid" v-if="previewObj.data_type === '表格填报'" :initTableHeader="previewObj.form_data" :preview="isHand"></TableInfo>
            </div>
            <div class="question-model">
              <QuestionRecord :taskId="taskid" :isHand="isHand" :initQuestionInfo="previewObj.question_data" :preview="true" v-if="previewObj.data_type === '测评问卷'"></QuestionRecord>
            </div>
          </el-tab-pane>

          <!-- 任务指标 -->
          <el-tab-pane name="taskIndex" v-if="previewObj.data_type === '文件上传' && previewObj.target">
            <span slot="label"><i class="el-icon-coordinate"></i> 任务指标</span>
            <RelateTarget ref="targetInfo" v-if="previewObj.target" :isShow="true" :isMark="true" :preivew="true"
              :target="previewObj.target" />
          </el-tab-pane>

          <!-- 子任务列表 -->
          <el-tab-pane name="subTask">
            <span slot="label"><i class="el-icon-medal"></i> {{ taskSize }}</span>
            <el-table :data="previewObj.child" stripe style="width: 100%;">
              <el-table-column prop="title" label="任务名称" min-width="280" align="left">
                <template slot-scope="{ row, $index}">
                  <span class="subTask" @click="linkToDetail(row.id)">{{ row.title }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="data_type" label="上报类型" min-width="90"></el-table-column>
              <el-table-column prop="classify_name" label="任务类别" min-width="90"></el-table-column>
              <el-table-column prop="emergency_level" label="紧急程度" min-width="90"></el-table-column>
              <el-table-column label="截至日期" min-width="180">
                <template slot-scope="{row}">
                  <span>{{ parseTime(row.end_time) }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" min-width="180">
                          <template slot-scope="scope">
                            <router-link :to="'/index-manager/checkIndex'">
                              <el-button type="default" size="small" icon="el-icon-document"></el-button>
                            </router-link>
                            <router-link :to="'/task-center/edit/'+scope.row.id">
                              <el-button type="primary" size="small" icon="el-icon-edit"></el-button>
                            </router-link>
                            <el-button type="danger" size="small" icon="el-icon-delete" @click="tagTaskDel(scope.row.id)"></el-button>
                          </template>
                        </el-table-column> -->
            </el-table>
            <!-- </template> -->
          </el-tab-pane>

          <!-- 跟踪问效显示 -->
          <el-tab-pane name="tracking" v-if="previewObj.issued_superior === -1" >
            <span slot="label"><i class="el-icon-s-flag"></i> 跟踪问效</span>
            <el-table :data="previewObj.outer_task" stripe style="width: 100%;">
              <el-table-column prop="id" label="任务ID" min-width="80"></el-table-column>
              <el-table-column prop="user" label="处理人" min-width="180"></el-table-column>
              <el-table-column label="处理时间" min-width="180">
                  <template slot-scope="{row}">
                      <span>{{ parseTime(row.time) }}</span>
                    </template>
              </el-table-column>
              <el-table-column label="操作" min-width="70">
                  <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="showTaskProcess(scope.row.id)">查看</el-button>
                  </template>
                </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col class="content-right" :xs="24" :sm="24" :md="24" :lg="6" :xl="6" v-if="isShowBaseInfo">
        <div class="desc">基本信息</div>
        <el-form ref="form" label-width="90px" class="baseinfo">
          <el-form-item label="任务名称">
            {{previewObj.title || '- -'}}
          </el-form-item>
          <el-form-item label="任务类别"> {{previewObj.classify_name || '- -'}}</el-form-item>
          <el-form-item label="上报类别"> {{previewObj.data_type || '- -'}}</el-form-item>
          <el-form-item label="紧急程度">
            <el-tag :type="previewObj.emergency_level | tagType">
              {{ previewObj.emergency_level }}
            </el-tag>
          </el-form-item>
          <el-form-item label="截止时间"> {{ parseTime(previewObj.end_time)}}</el-form-item>
          <el-form-item label="创建人"> {{previewObj.owner}}</el-form-item>
          <el-form-item label="创建时间"> {{ parseTime(previewObj.create_time)}}</el-form-item>
          <el-form-item label="发布状态">
            <el-tag :type="previewObj.status | tagType">
              {{ previewObj.status }}
            </el-tag>
            <!-- {{previewObj.is_publish | formatTime}} -->
          </el-form-item>
          <!-- <el-form-item label="是否完成">
            <el-switch :disabled="previewObj.overdue === '逾期' || previewObj.is_finish" v-model="previewObj.is_finish" @change="changeTaskStatus"></el-switch>
          </el-form-item> -->
          <el-form-item label="处理人">
            <div :class="{collapse: !isExpand}" :style="{overflow: previewObj.username && previewObj.username.length < 40 ? 'initial' : ''}">
              <el-tooltip :content="item" placement="right" effect="light" v-for="(item,index) in previewObj.username"
                :key="index">
                <div class="owner">{{ item }}</div>
              </el-tooltip>
            </div>
            <div v-if="previewObj.username && previewObj.username.length > 40" class="showMore" @click="isExpand = !isExpand">
              {{isExpand ? '收起' : '查看'}}更多处理人
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 流程监控 -->
    <process-monitor ref="process" :fromTask="true" :activities="activities" :processStatics="processStatics"></process-monitor>
  </div>
</template>
<script>
  import {
    postCreateTask,
    getTaskInfo,
    updateTaskPart,
    getPaperClassify
  } from '@/api/work.js'
  import { getTaskProcessInfo1 } from "@/api/workflow.js";
  import {
    getTable,
    getQuestion
  } from '@/api/question.js'
  import {
    parseTime,
    previewFile,
    getFileType
  } from '@/utils/index.js'
  export default {
    name: 'taskPreview',
    components: {
      'TableInfo': () => import('../showRecord/components/TableInfo.vue'),
      'QuestionRecord': () => import('@/views/markSys/questionRecord/index.vue'),
      'Pager': () => import("../approve/handler/Pager"),
      'ImageType': () => import('@/components/ImageType'),
      'FileUpload': () => import("@/components/FileUpload"),
      'RelateTarget': () => import("../components/relateTarget"),
      'process-monitor': () => import('../approve/handler/components/ProcessMinitor/index.vue'),
      'HistoryFile': () => import('../pendingTask/report/components/historyFile'),
      'TaskInfoFeedback': () => import("../components/TaskInfoFeedback"),
      'ProposedPager': () => import("../components/ProposedPager"),
    },
    data() {
      return {
        previewObj: {},
        activeName: 'baseInfo',
        taskid: null,
        isHand: null,
        dialogFormVisible: false,
        isExpand: false,
        historyFileNum: 0,
        pagerClassify: null,
        pagerClassifyOptions: [], // 套红文件模板列表
        processStatics: {
            curCount: 0,
            doneCount: 0,
            willCount: 0
        }, // 流程监控节点统计
        activities: [] // 流程监控数据
      }
    },
    computed: {
      createTime() {
        const date = new Date(this.previewObj.create_time)
        return parseTime(date, '{y}-{m}-{d}')
      },
      endTime() {
        const date = new Date(this.previewObj.end_time)
        return parseTime(date, '{y}-{m}-{d}')
      },
      // 返回通知对应任务类型
      noticeType() {
        const { classify_name, data_type } = this.previewObj
        if(data_type === '通知') {
          return classify_name
        }
        return 'other'
      },
      isQuestion() {
        return this.previewObj.data_type === '测评问卷' ? true : false
      },
      hasTaskFile() {
        return this.previewObj.taskFile && !!this.previewObj.taskFile.length
      },
      taskSize() {
        const size = this.previewObj.child && this.previewObj.child.length
        return '子任务(' + size + ')'
      },
      isShowBaseInfo() {
        const width = document.documentElement.clientWidth
        if (width < 1200) {
          if (this.activeName === 'baseInfo') return true
          return false
        }
        return true
      },
      // 判断是否从任务列表跳转到此页面
      isFromTaskList() {
        // 如果是，附件 文件为编辑模式
        return this.queryData.fromRoute === 'taskList'
      }
    },
    created() {
      // const id = this.$route.params && this.$route.params.id
      this.queryData = this.$route.params
      if(!this.queryData.targetId){
        this.$router.push({name: 'HomePage'})
        return
      }
      this.isHand = true
      this.taskid = this.queryData.targetId
      this.fetchData(this.taskid)
      this.requestPagerClassify()
    },
    methods: {
      parseTime,
      previewFile,
      // 返回历史上传文件记录数量
      getHistoryFileNum(num) {
        this.historyFileNum = num
      },
      // 选择套红模板
      handSelectPager(fileObj, pagerId) {
        const {
          id,
          fileType,
          url
        } = fileObj
        if (['doc', 'docx', 'pdf', 'xls', 'xlsx', 'pptx'].includes(fileType)) {
          const {
            href
          } = this.$router.resolve({
            name: 'FilePreview',
            query: {
              pagerId: pagerId,
              previewType: 1,
              fileId: id,
              isTemplate: true
            }
          })
          window.open(href, '_blank')
        } else {
          window.open(url, '_blank')
        }
      },
      // 打开任务流程监控
      showTaskProcess(taskId){
        getTaskProcessInfo1(taskId).then(
          res =>{
            const { curCount, doneCount, willCount, data } = res.data && res.data.data || {}
            this.activities = data
            this.processStatics = {
              taskId: taskId,
              curCount: curCount,
              doneCount: doneCount,
              willCount: willCount
            }
          }
        )
        this.$refs.process.dialogProcessVisible = true
        this.$refs.process.togglePage = false
      },
      // 完成任务开关
      changeTaskStatus(val) {
        updateTaskPart(this.taskid, {
          is_finish: +val
        }).then()
      },
      fetchData(id) {
        // 获取基础填信息
        getTaskInfo(id).then(res => {
          this.previewObj = res.data
          this.formatData(this.previewObj)
          const { username, issued_superior } = this.previewObj || {}
          // 如果处理人过多
          if(username.length > 40) {
            this.isExpand = false
          }
          // 如果有处理签，则设置activename
          if(issued_superior !== -1 && this.queryData.showPager) {
            this.activeName = 'dealWithSign'
          }
        })
      },
      // 编辑任务
      handleUpdateTask(index) {
        this.$router.push({
          path: `/task-center/edit/${index}`
        })
      },
      // 跳转到任务详情
      linkToDetail(id){
        this.isHand = true
        this.taskid = id
        this.fetchData(this.taskid)
        this.requestPagerClassify()
      },
      formatFile(str) {
        const file = getFileType(str, '/')
        return decodeURI(file)
      },
      formatData(obj) {
        const res = []
        obj.status = obj.is_publish ? '已发布' : '未发布'
        obj.taskFile.forEach(e => {
          res.push({
            id: e.id,
            name: this.formatFile(e.url),
            url: process.env.VUE_APP_IMAGE_URL + '/upload/' + e.url,
            fileType: getFileType(e.url, '.')
          })
        })
        obj.taskFile = res
        return obj
      },
      formatFile(str) {
        const file = getFileType(str, '/')
        return decodeURI(file)
      },
      // 获取套红模板列表
      requestPagerClassify() {
        getPaperClassify('').then(
          res => {
            this.pagerClassifyOptions = res.data.results
          }
        )
      }
    },
  }

</script>
<style lang="scss" scoped>
  .preview-task {
    .header {
      padding: 10px 18px;
      // border-bottom: 1px solid #ddd;
      font-size: 18px;
      font-weight: 600;
      line-height: 2;
      align-items: baseline;

      .overdue-text {
        display: inline-block;
        height: 19px;
        line-height: 19px;
        vertical-align: text-top;
        font-size: 12px;
        color: #fff;
        background: #ff6060;
        border-radius: 4px;
        padding: 1px 3px;
      }
    }

    .content {
      padding: 5px 0;

      &-left,
      &-right {
        // border-right: 1px solid #ccc;
      }

      &-left {
        min-height: 355px;

        .fileList {
          display: flex;

          .text {
            padding: 12px 0;
            flex-basis: 40px;
          }

          .items {
            width: 100%;
            margin-left: 20px;

            .item {
              display: flex;

              .name {
                padding: 12px 0;
                max-width: 500px;
                overflow: hidden;
                text-overflow: ellipsis;
                cursor: pointer;

                &:hover {
                  color: #409EFF;
                }
              }

              .toolBox {
                color: #6f6f6f;
                margin-left: auto;

                /* opacity: 0; */
                .el-dropdown {
                  color: #409EFF;
                  padding: 12px 0;
                }
              }

              &:hover {
                .toolBox {
                  opacity: 1;
                }
              }
            }
          }
        }

        .subTask {
          color: #409eff;
          cursor: pointer;
        }
        .fileUpload-history {
          .title {
            color: #409eff;

            .name {
              line-height: 20px;
              display: inline-block;
              list-style: none;
              font-size: 14px;
              font-weight: 500;
            }
          }
        }
      }

      &-right {
        .desc {
          padding: 10px 20px;
        }

        .baseinfo {
          padding: 0 20px;
        }
        .collapse {
          max-height: 208px;
          overflow: overlay;
        }
        .showMore {
          text-align: center;
          color: #999;
          cursor: pointer;
        }
        .owner {
          display: inline-block;
          width: 38px;
          height: 38px;
          background: #98d5e8;
          color: #fff;
          text-align: center;
          vertical-align: middle;
          line-height: 40px;
          font-size: 13px;
          border-radius: 50%;
          margin: 0 4px 4px 0;
        }
      }
    }
  }

</style>
<style>
  .el-form-item {
    margin: 0;
  }

  .el-form-item__label {
    text-align: left;
    font-size: 13px;
    color: #909090;
    font-weight: normal;
  }

  .el-form-item__content {
    font-size: 13px;
    word-break: break-all;
    word-wrap: break-word;
  }

  .el-tabs {
    margin: 0 20px;
  }

  .el-tabs__content {
    padding: 0 15px;
  }

  .el-tabs__nav-scroll {
    padding: 0 15px;
  }

  .el-tabs__item {
    height: 43px !important;
  }

  .el-divider--horizontal {
    margin: 22px 0;
  }

</style>
